package com.mmd.base.hander;

import com.mmd.base.auth.TokenTemplate;
import com.mmd.base.auth.UserContextHolder;
import com.mmd.base.pojo.entity.UserInfo;
import com.mmd.core.constant.KeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Component
public class MyAuthFilter extends GenericFilterBean {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("MyAuthFilter过滤器执行");
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader(KeyConstant.AUTHENTICATION);
        // 向上下文存储Authentication
        if(!StringUtils.isEmpty(token)){
            String value = redisTemplate.opsForValue().get(token);
            if(!StringUtils.isEmpty(value)){
                UserInfo<Object> subject = TokenTemplate.getSubject(value, Object.class);
                subject.setAuthentication(token);
                UserContextHolder.setSecurityContextHolder(subject,value);
            }
        }
        log.info("MyAuthFilter过滤器获取到用户{}={}",KeyConstant.AUTHENTICATION,token);
        chain.doFilter(request,response);
    }
}
